<template>
  <!-- 设备添加 -->
  <el-dialog
    top="15vh"
    :title="dialogTitle"
    :visible.sync="dialogShow"
    width="561px"
    height="262px"
    destroy-on-close
    @close="cancleHandle"
    :close-on-click-modal="false"
  >
    <div class="equipmentAdd_inner">
      <el-form ref="form" label-width="120px" :model="form" :rules="formRules" :size="formItemSize">
        <el-form-item :label="$t('equipmentManagement.shebei36')" prop="serialNo">
          <el-input
            :disabled="actionType === 'edit' || !isSave"
            v-model="form.serialNo"
            style="width: 320px"
            :placeholder="$t('equipmentManagement.shebei37')"
          />
          <el-button
            v-if="user_superAdmin == '1' && actionType === 'add'"
            style="margin-left: 20px"
            type="primary"
            @click="generateData('save')"
            >{{
              isSave ? $t('equipmentManagement.shebei52') : $t('equipmentManagement.shebei27')
            }}</el-button
          >
        </el-form-item>

        <el-form-item
          v-if="user_superAdmin === '0'"
          :label="$t('equipmentManagement.shebei38')"
          prop="privateKey"
        >
          <el-input
            v-model="form.privateKey"
            style="width: 320px"
            :placeholder="$t('equipmentManagement.shebei39')"
          />
        </el-form-item>

        <el-form-item
          v-if="user_superAdmin == '1'"
          :label="$t('equipmentManagement.shebei97')"
          prop="deviceType"
        >
          <el-select
            disabled
            v-model="form.deviceType"
            :placeholder="$t('equipmentManagement.shebei111')"
            style="width: 320px"
          >
            <el-option
              v-for="item in deviceTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="user_superAdmin == '1'"
          :label="$t('equipmentManagement.shebei112')"
          prop="deviceOrderControl"
        >
          <el-select
            style="width: 320px"
            v-model="form.deviceOrderControl"
            :placeholder="$t('equipmentManagement.shebei113')"
            @change="generateData"
            :disabled="form.deviceType == '2'"
          >
            <el-option
              v-for="item in deviceOrderControlList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="user_superAdmin == '1'"
          :label="$t('equipmentManagement.shebei98')"
          prop="clientVersion"
        >
          <el-input
            v-model="form.clientVersion"
            disabled
            style="width: 320px"
            :placeholder="$t('equipmentManagement.shebei114')"
          />
        </el-form-item>

        <el-form-item
          v-if="user_superAdmin == '1' && isShowBusinessStatus"
          :label="$t('equipmentManagement.shebei99')"
          prop="businessStatus"
        >
          <el-select
            style="width: 320px"
            v-model="form.businessStatus"
            :placeholder="$t('equipmentManagement.shebei115')"
          >
            <el-option
              v-for="item in businessStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button plain :size="optionButtonSize" @click="cancleHandle"
        >{{ $t('equipmentManagement.shebei40') }}
      </el-button>
      <el-button type="primary" :size="optionButtonSize" v-loading="addLoading" @click="submitHandle"
        >{{ $t('equipmentManagement.shebei41') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'BLZMasterIndex',

  data() {
    return {
      dialogShow: false,
      dialogTitle: this.$t('equipmentManagement.shebei35'),
      deviceTypeList: [
        {
          label: '⼝内扫描仪',
          value: '1',
        },
        {
          label: '桌⾯扫描仪',
          value: '2',
        },
      ],
      deviceOrderControlList: [
        {
          label: '有限制',
          value: '1',
        },
        {
          label: '无限制',
          value: '0',
        },
      ],
      businessStatusList: [
        {
          label: '有限制',
          value: '1',
        },
        {
          label: '无限制',
          value: '0',
        },
      ],
      form: {
        serialNo: '', // 序列号
        privateKey: '',
        deviceType: '',
        deviceOrderControl: '',
        clientVersion: '',
        businessStatus: '',
        deviceLocation: '',
      },
      oldForm: {},
      formRules: {
        serialNo: [
          {
            required: true,
            message: this.$t('equipmentManagement.shebei37'),
            trigger: ['blur', 'change'],
          },
        ],
        privateKey: [
          {
            required: true,
            message: this.$t('equipmentManagement.shebei39'),
            trigger: ['blur', 'change'],
          },
        ],
        deviceType: [
          {
            required: true,
            message: this.$t('equipmentManagement.shebei111'),
            trigger: ['blur', 'change'],
          },
        ],
        deviceOrderControl: [
          {
            required: true,
            message: this.$t('equipmentManagement.shebei113'),
            trigger: ['blur', 'change'],
          },
        ],
        clientVersion: [
          {
            required: true,
            message: this.$t('equipmentManagement.shebei114'),
            trigger: ['blur', 'change'],
          },
        ],
        businessStatus: [
          {
            required: true,
            message: this.$t('equipmentManagement.shebei115'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      // 控制业务状态是否显示
      isShowBusinessStatus: true,
      actionType: 'add',

      user_superAdmin: '',

      // 控制序列号那里的按钮
      isSave: true,
      addLoading: false,
    };
  },
  props: {
    detailData: {
      type: Object,
    },
  },
  watch: {
    // detailData: {
    //   handler(newValue, oldValue) {
    //     this.initData();
    //   },
    //   deep: true,
    // },
  },

  created() {
    this.user_superAdmin = localStorage.getItem('user_superAdmin');
    this.initData();
  },

  methods: {
    // 初始化表单数据
    initData() {
      if (this.detailData && Object.keys(this.detailData).length > 0) {
        this.actionType = 'edit';
        // 说明是编辑点进来的
        this.form = this.detailData;
        this.oldForm = JSON.parse(JSON.stringify(this.form));
        this.dialogTitle = this.$t('equipmentManagement.shebei43');
      } else {
        this.actionType = 'add';
        this.dialogTitle = this.$t('equipmentManagement.shebei35');
        // this.form = {};
        this.form = {
          serialNo: '', // 序列号
          privateKey: '',
          deviceType: '',
          deviceOrderControl: '',
          clientVersion: '',
          businessStatus: '',
          deviceLocation: '',
        };
        this.$refs['form'] && this.$refs['form'].resetFields();
      }

      if (this.form.deviceType == '1') {
        this.isShowBusinessStatus = true;
      } else if (this.form.deviceType == '2') {
        this.isShowBusinessStatus = false;
      }
    },
    // 根据序列号生成数据
    generateData(type) {
      this.$http
        .get('/device/verifySerialNumber', {
          params: this.form,
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.form['clientVersion'] = res.data.clientVersion;
            this.form['deviceType'] = res.data.deviceType;
            this.form['deviceLocation'] = res.data.deviceLocation;
            if (this.form.deviceType == '1') {
              this.isShowBusinessStatus = true;
              if (type !== 'save') {
                this.form.businessStatus = '';
              }

              // 口扫
              if (this.form.deviceOrderControl === '1') {
                this.businessStatusList = [
                  {
                    label: '有限制',
                    value: '1',
                  },
                  {
                    label: '无限制',
                    value: '0',
                  },
                ];
              } else if (this.form.deviceOrderControl === '0') {
                this.businessStatusList = [
                  {
                    label: '无限制',
                    value: '0',
                  },
                ];
              }
            } else if (this.form.deviceType == '2') {
              this.form['deviceOrderControl'] = res.data.deviceOrderControl;
              // 桌扫
              this.form.businessStatus = '';
              this.isShowBusinessStatus = false;
            }

            if (type === 'save') {
              this.isSave = !this.isSave;
            }
          }
        })
        .catch((err) => {
          console.log('err', err);
        });
    },

    // 取消
    cancleHandle() {
      this.dialogShow = false;
      this.form = {
        serialNo: '', // 序列号
        deviceType: '',
        deviceOrderControl: '',
        clientVersion: '',
        businessStatus: '',
        deviceLocation: '',
      };
      this.$refs['form'] && this.$refs['form'].resetFields();
      this.isSave = true;
      this.$emit('closeAdd');
    },
    // 校验旧数据和新数据是否一致
    isDeepEqual() {
      let bool = true;
      if (
        this.form.deviceOrderControl !== this.oldForm.deviceOrderControl ||
        this.form.businessStatus !== this.oldForm.businessStatus
      ) {
        bool = false;
      }
      return bool;
    },
    // 保存
    submitHandle() {
      this.$refs.form.validate((valid) => {
        if (valid) {
        
          if (this.isSave && !this.form.id && this.user_superAdmin == '1') {
            return this.$message({
              message: this.$t('equipmentManagement.shebei141'),
              type: 'warning',
            });
          }
          let bool = this.isDeepEqual(this.form, this.oldForm);

          if (bool) {
            this.dialogShow = false;
          } else {
            if(this.addLoading || !this.dialogShow){
              return false;
            }
            this.addLoading = true;
            if (this.user_superAdmin == '1') {
              // 后台
              if (this.actionType === 'add') {
                this.$http
                  .post('/device/save', this.form)
                  .then(({ data: res }) => {
                    if (res.code !== 0) {
                      this.addLoading = false;
                      return this.$message.error(res.msg);
                    } else {
                      this.$message.success(this.$t('equipmentManagement.shebei42'));
                      this.$emit('getDetailList');
                      this.cancleHandle();
                      this.addLoading = false;
                    }
                  })
                  .catch((err) => {
                    this.addLoading = false;
                    console.log('err', err);
                  });
              } else if (this.actionType === 'edit') {
                this.$http
                  .post('/device/update', this.form)
                  .then(({ data: res }) => {
                    if (res.code !== 0) {
                      this.addLoading = false;
                      return this.$message.error(res.msg);
                    } else {
                      this.$message.success(this.$t('equipmentManagement.shebei53'));
                      this.$emit('getDetailList');
                      this.cancleHandle();
                      this.addLoading = false;
                    }
                  })
                  .catch((err) => {
                    this.addLoading = false;
                    console.log('err', err);
                  });
              }
            } else if (this.user_superAdmin == '0') {
              // 前台
              this.$http
                .post('/device/bind', this.form)
                .then(({ data: res }) => {
                  if (res.code !== 0) {
                    this.addLoading = false;
                    return this.$message.error(res.msg);
                  } else {
                    
                    this.$message.success(this.$t('equipmentManagement.shebei42'));
                    this.$emit('getDetailList');
                    this.cancleHandle();
                    this.addLoading = false;
                  }
                })
                .catch((err) => {
                  this.addLoading = false;
                  console.log('err', err);
                });
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="scss"></style>
